import * as types from './ActionTypes'
//导入异步获取数据
import NetUitl from '../common/fetchcomponent';
export let popupAlert = ({title,content})=>{
  return (dispatch,getState)=>{
    dispatch({
      type:types.SHOW_ALERT,
      payload:{
        title:title,
        content:content
      }
    })
    setTimeout(function(){
      dispatch({
        type:'HIDE_ALERT'
      })
    },1500)
  }
}
export let fetchCreactions = ({feedType})=>{
  return (dispatch,getState)=>{
    //设置url
    let url = ''
    let isLoadingTail = false
    let isRefreshing = false
    let creation //数据排序
    let cid = ''
    //获取数据列表
    const {videoList} = getState().get('creations')
    const {user} = getState().get('app')
    //设置初始化数据
    if(feedType === 'recent'){
      isRefreshing = true
      creation = videoList[0]
    }else{
      isLoadingTail = false
      creation = videoList[videoList.length-1]
    }
    //当前数据是否为空，是否第一次请求
    if(creation && creation._id){
      cid = creation._id
    }
    //告知要发起请求，
    dispatch({
      type:types.FETCH_CREATIONS_START,
      payload:{
        isLoadingTail:isLoadingTail,
        isRefreshing:isRefreshing
      }
    })
    
    NetUitl.post(url,{
      accessToken:132456798,
      feedType:feedType,
      cid:cid
    }).then((data)=>{
      if(data && data.success){
        //如果有数据
        if(data.data.length>0){
          data.data.map(function(item){
            const votes = item.votes || []
            if(user && votes.indexOf(user._id)>-1){
              item.voted = true
            }else{
              item.voted = false
            }
            return item
          })
          let newVideoList
          //刷新或加载
          if(feedType === 'recent'){
            newVideoList = data.data.concat(videoList)
          }else{
            newVideoList = videoList.concat(data.data)
          }
        }
      }
      dispatch({
        type:types.FETCH_CREATIONS_FULFILLED,
        payload:{
          videoList:newVideoList,
          videoTotal:data.total,
          isLoadingTail:false,
          isRefreshing:false
        }
      }) 
    }).catch(err=>{
      dispatch({
        type:types.FETCH_CREATIONS_REGECTED,
        payload:{
          err:err,
          isLoadingTail:false,
          isRefreshing:false
        }
      })
    })
  }
}